package cn.gdcp.listview;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class MyAdapter extends BaseAdapter {
    private ArrayList<Student> studentArrayList;
    private Context context;
    private IOnDelListener listener;

    public MyAdapter(Context context, ArrayList<Student> studentArrayList, IOnDelListener listener){
        this.context = context;
        this.studentArrayList = studentArrayList;
        this.listener = listener;
    }
    public void changeData(ArrayList<Student> studentArrayList){
        this.studentArrayList = studentArrayList;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return studentArrayList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    int count = 0;

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        Log.e("MyAdapter","getview" + i + "count = " + count);

        if (view == null){
            count++;
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.my_list_item,viewGroup,false);

            StuViewHolder holder = new StuViewHolder();

            holder.headView = view.findViewById(R.id.headView);
            holder.nameView = view.findViewById(R.id.nameView);
            holder.ageView = view.findViewById(R.id.ageView);
            holder.ivDel = view.findViewById(R.id.iv_del);

            view.setTag(holder);
        }

        Student student = studentArrayList.get(i);

        StuViewHolder holder = (StuViewHolder) view.getTag();

        holder.headView.setImageResource(student.getImgId());
        holder.ageView.setText(String.valueOf(student.getAge()));
        holder.nameView.setText(student.getName());

        holder.ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.del(i);
            }
        });

        return view;
    }
}
